package com.doublefish.doublefishrobot.ui.video;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.appcompat.app.ActionBar;

import com.doublefish.doublefishrobot.R;
import com.doublefish.doublefishrobot.base.BaseActivity;
import com.doublefish.doublefishrobot.ui.video.bean.VideoInfoBean;
import com.doublefish.doublefishrobot.ui.video.bean.VideoPlayerItemBean;
import com.doublefish.doublefishrobot.ui.video.utils.VideoManager;
import com.doublefish.doublefishrobot.ui.video.widget.VideoPlayerView;
import com.doublefish.doublefishrobot.widget.ActionListDialog;
import com.doublefish.doublefishrobot.widget.CommonDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 作者:dugaofeng on 2024/10/29 14:44
 */
public class VideoPlayerActivity extends BaseActivity {

    @BindView(R.id.view_top)
    ViewGroup topView;

    @BindView(R.id.tv_title)
    TextView titleTv;

    @BindView(R.id.tv_right)
    TextView rightTv;

    @BindView(R.id.fl_video)
    FrameLayout videoFl;

    @BindView(R.id.tv_desc)
    TextView descTv;

    @BindView(R.id.view_video_content)
    VideoPlayerView videoPlayerView;

    @BindView(R.id.tv_clarity)
    TextView clarityTv;

    private String videoCode;
    private String videoName;
    private VideoInfoBean currentVideoInfoBean;

    private boolean isHD = false; //是否高清视频

    private boolean isFullScreen = false;

    public static Intent createIntent(Context context, String videoName, String videoCode) {
        Intent intent = new Intent(context,VideoPlayerActivity.class);
        intent.putExtra("videoName", videoName);
        intent.putExtra("videoCode", videoCode);
        return intent;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_video_player;
    }

    @Override
    protected void initView() {
        rightTv.setText(R.string.video_contrast);

        layoutViews();
    }

    @Override
    protected void initListener() {
        videoPlayerView.setOnVideoPalyerViewListner(new VideoPlayerView.OnVideoPalyerViewListner() {
            @Override
            public void onFullScreenBtnClick(boolean fullScreen) {
                setFullscreen(fullScreen);
            }

            @Override
            public void onSpeedBtnClick() {
                showSpeedDialog();
            }
        });
    }

    @Override
    protected void initData() {
        Intent intent = getIntent();
        videoCode = intent.getStringExtra("videoCode");
        videoName = intent.getStringExtra("videoName");

        titleTv.setText(videoName);

        //显示说明信息 ，标清和高清的信息是一样的, 随便获取一个
        VideoInfoBean video = VideoManager.getInstance().getVideoInfoBean(videoCode, false);
        descTv.setText(video.getDesc());

        //准备播放
        getPlayerVideoSource(VideoManager.DFGetVideoSourceType_Auto);
    }

    @Override
    protected void onDestroy() {
        if (videoPlayerView != null) {
            videoPlayerView.stop();
        }
        unRegisterSensorManager();
        super.onDestroy();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        layoutViews();
    }

    private void setFullscreen(boolean fullScreen) {
        isFullScreen = fullScreen;
        if (fullScreen) {
            registerSensorManager();
        } else {
            unRegisterSensorManager();
            mFlag = 1;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
        layoutViews();
    }

    private void layoutViews() {
        if (isFullScreen) {
            topView.setVisibility(View.GONE);
            //全屏状态
            DisplayMetrics dm = new DisplayMetrics();//屏幕度量
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;//宽度
            int screenHeight = dm.heightPixels;//高度
            if (mFlag == 1) {
                showSystemUI();
            } else if (mFlag == 2 || mFlag == 4) {
                hideSystemUI();
            }
            //调整播放器的大小为全屏
            ViewGroup.LayoutParams layoutParams = videoFl.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = screenHeight;
            videoFl.setLayoutParams(layoutParams);
        } else {
            topView.setVisibility(View.VISIBLE);
            showSystemUI();
            //非全屏状态
            DisplayMetrics dm = new DisplayMetrics();//屏幕度量
            getWindowManager().getDefaultDisplay().getMetrics(dm);
            int screenWidth = dm.widthPixels;//宽度
//            int screenHeight = dm.heightPixels;//高度
            //调整播放器的大小 使宽高比为16:9
            ViewGroup.LayoutParams layoutParams = videoFl.getLayoutParams();
            layoutParams.width = screenWidth;
            layoutParams.height = screenWidth * 9 / 16;
            videoFl.setLayoutParams(layoutParams);
        }
    }

    private void showSpeedDialog() {
        String title = getString(R.string.select_playback_speed);
        List<String> list= videoPlayerView.speedList();

        ActionListDialog dialog = new ActionListDialog(this, title, list, new ActionListDialog.OnActionListDialogListner() {
            @Override
            public void onActionBtnClick(int postion, String text) {
                videoPlayerView.setSpeed(postion);
            }

            @Override
            public void onCancelBtnClick() {

            }
        });
        dialog.show();
    }

    //准备播放
    private void getPlayerVideoSource(int getVideoSourceType) {
        VideoManager.getInstance().getPlayerVideo(videoCode, getVideoSourceType, new VideoManager.OnGetPalyerVideoListner() {
            @Override
            public void onSuccess(VideoInfoBean videoInfoBean, VideoPlayerItemBean itemBean) {
                currentVideoInfoBean = videoInfoBean;
                isHD = videoInfoBean.isHD();
                try {
                    clarityTv.setText(isHD ? getString(R.string.high_definition) : getString(R.string.standard_definition));
                    videoPlayerView.setVideoPlayerItemBean(itemBean);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onFail(int videoSourceError) {
                try {
                    if (videoSourceError == VideoManager.DFVideoSourceError_None) {
                        showToast(getString(R.string.error_video_info));
                    } else if (videoSourceError == VideoManager.DFVideoSourceError_Need_Download) {
                        //弹窗提示视频下载
                        if (getVideoSourceType == VideoManager.DFGetVideoSourceType_Auto) {
                            showDownloadDialog(videoCode, false);
                        } else if (getVideoSourceType == VideoManager.DFGetVideoSourceType_HD_NEED) {
                            showDownloadDialog(videoCode, true);
                        }
                    } else if (videoSourceError == VideoManager.DFVideoSourceError_NetError) {
                        showToast(getString(R.string.network_error));
                    } else if (videoSourceError == VideoManager.DFVideoSourceError_Downloading) {
                        showToast(getString(R.string.download2___));
                    } else if (videoSourceError == VideoManager.DFVideoSourceError_Download_Error) {
                        showToast(getString(R.string.fail_dowload));
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @OnClick(R.id.tv_right)
    public void onRightBtnClick() {
        if (currentVideoInfoBean == null) {
            showToast(getString(R.string.error_video_info));
            return;
        }
        if (currentVideoInfoBean.getIsExistVideo() != 99) {
            showToast(getString(R.string.download___));
            return;
        }
        videoPlayerView.pause();

        Intent intent = VideoContrastActivity.createIntent(this, videoName, videoCode, currentVideoInfoBean.getLocalPath());
        startActivity(intent);
    }

    @OnClick(R.id.ll_back)
    public void onBackClick() {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && isFullScreen) {
            setFullscreen(false);
            videoPlayerView.exitFullScreen();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //region 高清视频相关接口
    @OnClick(R.id.tv_clarity)
    public void onClarityTvClick() {
        if (isHD) {
            return;
        }
        showClarityDialog();
    }

    private void showClarityDialog() {
        String title = getString(R.string.switch_video_clarity);
        List<String> list= new ArrayList<>();
        list.add(getString(R.string.standard_definition));
        list.add(getString(R.string.high_definition));

        ActionListDialog dialog = new ActionListDialog(this, title, list, new ActionListDialog.OnActionListDialogListner(){
            @Override
            public void onCancelBtnClick() {

            }
            @Override
            public void onActionBtnClick(int postion, String text) {
                if (postion == 0) {
                    getPlayerVideoSource(VideoManager.DFGetVideoSourceType_Auto);
              } else if (postion == 1) {
                    getPlayerVideoSource(VideoManager.DFGetVideoSourceType_HD_NEED);
                }
            }
        });
        dialog.show();
    }

    private void showDownloadDialog(String videoCode, boolean isHD) {
        if (isHD) {
            VideoInfoBean infoBean = VideoManager.getInstance().getVideoInfoBean(videoCode, isHD);
            String title = getString(R.string.video_tips);
            String content = String.format(getString(R.string.dowload_tips_2), fileSizeText(infoBean.getSize()));
            CommonDialog commomDialog = new CommonDialog(this, title, content, new CommonDialog.OnCloseListener() {
                @Override
                public void onClick(Dialog dialog, boolean confirm) {
                    if (confirm) {
                        getPlayerVideoSource(VideoManager.DFGetVideoSourceType_HD_FORCE);
                    }
                }
            });
            commomDialog.show();
            return;
        }

        VideoInfoBean norVideoBean = VideoManager.getInstance().getVideoInfoBean(videoCode, false);
        VideoInfoBean hdVideoBean = VideoManager.getInstance().getVideoInfoBean(videoCode, true);
        String title = getString(R.string.video_tips);
//        String content = "下载该视频会消耗您的流量";

        List<String> list= new ArrayList<>();
        list.add(getString(R.string.standard_definition) + "(" + fileSizeText(norVideoBean.getSize()) + "）");
        list.add(getString(R.string.high_definition) + "(" + fileSizeText(hdVideoBean.getSize()) + "）");

        ActionListDialog dialog = new ActionListDialog(this, title, list, new ActionListDialog.OnActionListDialogListner(){
            @Override
            public void onCancelBtnClick() {

            }
            @Override
            public void onActionBtnClick(int postion, String text) {
                if (postion == 0) {
                    getPlayerVideoSource(VideoManager.DFGetVideoSourceType_NORMAL_FORCE);
                } else if (postion == 1) {
                    getPlayerVideoSource(VideoManager.DFGetVideoSourceType_HD_FORCE);
                }
            }
        });
        dialog.show();
    }

    private String fileSizeText(long size) {
        long kb = size / 1024;  //转为kb
        if (kb > 1024) {
            long mb = kb / 1024;
            return mb + "MB";
        } else {
            return kb + "KB";
        }
    }


    //endregion


    //region 重力感应
    private SensorManager sensorManager;
    private Sensor sensor;
    SensorEventListener listener;
    private int mFlag = 1;  //默认1 正常竖屏 （0.无变化\变化小 1.正常竖屏 2.右横屏 3.倒立竖屏 4.左横屏）
    private void registerSensorManager() {
        //使用加速度传感器判断屏幕方向
        sensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
        sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        listener = new SensorEventListener() {
            @Override
            public void onSensorChanged(SensorEvent sensorEvent) {
                float[] values = sensorEvent.values;
                int orientation = 0;
                float X = -values[0];
                float Y = -values[1];
                float Z = -values[2];
                float magnitude = X*X + Y*Y;
                // Don't trust the angle if the magnitude is small compared to the y value
                if (magnitude * 4 >= Z*Z) {
                    float OneEightyOverPi = 57.29577957855f;
                    float angle = (float)Math.atan2(-Y, X) * OneEightyOverPi;
                    orientation = 90 - (int)Math.round(angle);
                    // normalize to 0 - 359 range
                    while (orientation >= 360) {
                        orientation -= 360;
                    }
                    while (orientation < 0) {
                        orientation += 360;
                    }
                }
                onOrientationChanged(orientation);
            }

            @Override
            public void onAccuracyChanged(Sensor sensor, int i) {

            }
        };
        sensorManager.registerListener(listener, sensor, SensorManager.SENSOR_DELAY_UI);
    }

    private void unRegisterSensorManager() {
        if (listener != null) {
            sensorManager.unregisterListener(listener);
            listener = null;
        }
    }

    private void onOrientationChanged(int orientation) {
        int flag = 0;
        if (orientation > 0 && orientation < 45) {
            flag = 1;  //正常竖屏
        } else if (orientation > 45 && orientation < 135) {
            flag = 2;  //右横屏
        } else if (orientation > 135 && orientation < 225) {
            flag = 3;  //倒立竖屏
        } else if (orientation > 225 && orientation < 315) {
            flag = 4;  //左横屏
        } else if (orientation > 315 && orientation < 360) {
            flag = 1;  //正常竖屏
        }
//        Log.i("OrientationListener","" + orientation);
        //倒立竖屏 不做处理
        if (flag == 1 && mFlag != 1) {
            mFlag = 1;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else if (flag == 2 && mFlag != 2) {
            mFlag = 2;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE);
        } else if (flag == 4 && mFlag != 4) {
            mFlag = 4;
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        }
    }


    //全屏
    /**
     * 隐藏系统ui
     */
    private void hideSystemUI() {
        //隐藏ActionBar 如果使用了NoActionBar的Theme则不需要隐藏actionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        //TODO：View.setSystemUiVisibility(int visibility)中，visibility是Mode与Layout任意取值的组合，可传入的实参为：

        // Mode属性
        //View.SYSTEM_UI_FLAG_LOW_PROFILE：状态栏显示处于低能显示状态(low profile模式)，状态栏上一些图标显示会被隐藏。
        //View.SYSTEM_UI_FLAG_FULLSCREEN：Activity全屏显示，且状态栏被隐藏覆盖掉。等同于（WindowManager.LayoutParams.FLAG_FULLSCREEN）
        //View.SYSTEM_UI_FLAG_HIDE_NAVIGATION：隐藏虚拟按键(导航栏)。有些手机会用虚拟按键来代替物理按键。
        //View.SYSTEM_UI_FLAG_IMMERSIVE：这个flag只有当设置了SYSTEM_UI_FLAG_HIDE_NAVIGATION才起作用。
        // 如果没有设置这个flag，任意的View相互动作都退出SYSTEM_UI_FLAG_HIDE_NAVIGATION模式。如果设置就不会退出。
        //View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY：这个flag只有当设置了SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION 时才起作用。
        // 如果没有设置这个flag，任意的View相互动作都坏退出SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION模式。如果设置就不受影响。

        // Layout属性
        //View.SYSTEM_UI_FLAG_LAYOUT_STABLE： 保持View Layout不变，隐藏状态栏或者导航栏后，View不会拉伸。
        //View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN：让View全屏显示，Layout会被拉伸到StatusBar下面，不包含NavigationBar。
        //View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION：让View全屏显示，Layout会被拉伸到StatusBar和NavigationBar下面。
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            decorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LOW_PROFILE
//                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                            | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
            );
        }
        //解决在华为手机上横屏时，状态栏不消失的问题
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //隐藏状态栏

    }

    /**
     * 显示系统UI
     */
    private void showSystemUI() {
        //显示ActionBar 如果使用了NoActionBar的Theme则不需要显示actionBar
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.show();
        }
        View decorView = getWindow().getDecorView();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            // This snippet shows the system bars. It does this by removing all the flags
            // except for the ones that make the content appear under the system bars.
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        }
        //解决在华为手机上横屏时，状态栏不消失的问题
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); //显示状态栏
    }


    //endregion
}
